import { defineStore } from 'pinia'
import { useUserStore } from './user'
import { usePurchasedStore } from './purchased'

interface PaymentResult {
    success: boolean;
    order_id?: string;
    error_msg?: string;
}

interface WxPaymentData {
    timeStamp: string;
    nonceStr: string;
    package: string;
    signType: string;
    paySign: string;
    order_id: string;
}

export const usePaymentStore = defineStore('payment', () => {
    const userStore = useUserStore()
    const purchasedStore = usePurchasedStore()

    // 处理商品购买
    async function handleBuy(productId: string, price: number) {
        if (!userStore.userInfo?.access_token) {
            uni.showToast({
                title: '请先登录',
                icon: 'none'
            })
            return false
        }

        try {
            // 1. 创建订单
            const orderRes = await uni.request({
                url: 'https://52d47b77.r34.cpolar.top/api/orders/',
                method: 'POST',
                header: {
                    'Authorization': `Bearer ${userStore.userInfo.access_token}`,
                    'Content-Type': 'application/json'
                },
                data: {
                    product_id: productId,
                    amount: price
                }
            })
            console.log(orderRes, 555567987964646)
            if (orderRes.statusCode !== 200) {
                throw new Error('创建订单失败')
            }

            const orderData = orderRes.data as WxPaymentData

            // 2. 调用微信支付
            const paymentResult = await handleWxPayment(orderData)

            if (paymentResult.success) {
                try {
                    // 3. 支付成功后创建购买记录
                    // await createUserProduct(productId, orderData.order_id)
                    // 4. 刷新商品列表
                    await purchasedStore.fetchPurchasedProducts()

                    // 5. 检查商品状态
                    const status = await purchasedStore.checkProductStatus(productId)
                    // console.log(status, 'status555587964646777711111')
                    if (status.is_purchased) {
                        uni.showToast({
                            title: '购买成功',
                            icon: 'success'
                        })
                        return true
                    } else {
                        // 如果后端还没更新状态，等待一会再检查
                        await new Promise(resolve => setTimeout(resolve, 1500))
                        await purchasedStore.fetchPurchasedProducts()
                        return true
                    }
                } catch (error) {
                    console.error('处理购买后流程失败:', error)
                    // 即使后续处理失败，由于支付已成功，我们仍然返回成功
                    uni.showToast({
                        title: '购买成功',
                        icon: 'success'
                    })
                    return true
                }
            } else {
                throw new Error(paymentResult.error_msg || '支付失败')
            }
        } catch (error: any) {
            uni.showToast({
                title: error.message || '购买失败',
                icon: 'none'
            })
            return false
        }
    }

    // 处理微信支付
    async function handleWxPayment(orderData: WxPaymentData): Promise<PaymentResult> {
        return new Promise((resolve) => {
            uni.requestPayment({
                provider: 'wxpay',
                orderInfo: orderData,  // 直接传入完整的支付数据
                success: () => {
                    resolve({
                        success: true,
                        order_id: orderData.order_id
                    })
                },
                fail: (err) => {
                    resolve({
                        success: false,
                        error_msg: err.errMsg || '支付取消'
                    })
                }
            })
        })
    }

    // 创建用户购买记录
    async function createUserProduct(productId: string, orderId: string) {
        try {
            const res = await uni.request({
                url: 'https://52d47b77.r34.cpolar.top/api/user-products/',
                method: 'POST',
                header: {
                    'Authorization': `Bearer ${userStore.userInfo?.access_token}`,
                    'Content-Type': 'application/json'
                },
                data: {
                    product_id: productId,
                    phone: userStore.userInfo?.phone
                }
            })

            if (res.statusCode !== 201) {
                console.error('创建购买记录失败:', res)
                throw new Error('创建购买记录失败')
            }
        } catch (error) {
            console.error('创建购买记录失败:', error)
            throw error
        }
    }

    return {
        handleBuy
    }
})